package service

import (
	"douyin/models"
	"douyin/repository/mysql"

	"go.uber.org/zap"
	"golang.org/x/sync/errgroup"
)

// FavoriteAction 赞操作
func FavoriteAction(p *models.FavoriteRequest, userId int64) (err error) {
	g := new(errgroup.Group) //创建等待组
	//1.action_type==1,点赞
	if p.ActionType == 1 {
		g.Go(func() error {
			if err := mysql.Favorite(p.VideoId, userId); err != nil {
				return err
			}
			return nil
		})
		//点赞操作，就默认都成功了
		g.Go(func() error {
			//点赞成功，维护favorite_count属性
			if err := mysql.VideoFavoriteCount(p.VideoId, true); err != nil {
				return err
			}
			return nil
		})
		if err = g.Wait(); err != nil {
			zap.L().Error("service.Favorite failed", zap.Error(err))
			return err
		}
	}
	//2.action_type==2,取消点赞
	if p.ActionType == 2 {
		g.Go(func() error {
			if err := mysql.UnFavorite(p.VideoId, userId); err != nil {
				return err
			}
			return nil
		})
		g.Go(func() error {
			//点赞成功，维护favorite_count属性
			if err := mysql.VideoFavoriteCount(p.VideoId, false); err != nil {
				return err
			}
			return nil
		})
		if err = g.Wait(); err != nil {
			zap.L().Error("service.UnFavorite failed", zap.Error(err))
			return err
		}
	}
	return
}

// FavoriteList 点赞视频列表
func FavoriteList(userId, otherId int64) (videoList []models.Video, err error) {
	//1.根据otherId, 查找Favorites表,得到用户点赞的所有视频Id
	vidIds, err := mysql.SelectFavorite(otherId)
	if err != nil {
		zap.L().Error("mysql.SelectPublisher failed", zap.Error(err))
		return
	}
	//2.根据Ids,查找视频，返回Video切片
	videoList, err = mysql.SelectVideos(vidIds, userId)
	if err != nil {
		zap.L().Error("mysql.SelectVideos failed", zap.Error(err))
		return
	}
	return
}
